#!/usr/bin/env python
# _*_ coding: UTF-8 _*_

import os, sys, pty
import time, getopt, threading

from SSHBatch.Configure import Configure
from SSHBatch.Reactor import Reactor
from SSHBatch.SSHAgent import SSHAgent
from SSHBatch.KBAgent import KBAgent
from SSHBatch.Log import Log
from SSHBatch.Invoker import Invoker

SSHBATCH_WELCOME = "SSHBatch v0.1.0 April 2008, GPL v3 licensed\n"
SSHBATCH_WELCOME += "Author: yingyuan.cheng@gmail.com\n"

def usage(argv):
    print "Usage: %s -c config-file" % argv[0]
    sys.exit(1)

def feature_test(ft):
    try:
        import readline
        ft["has_readline"] = True
    except e:
        ft["has_readline"] = False

def main(argv):
    print SSHBATCH_WELCOME,
    
    (options, params) = getopt.getopt(argv[1:], "c:")
    if not (len(params) == 0):
        print "Unknown parameters", params
        usage(argv)
    config_fpath = ""
    for optkey, optvalue in options:
        if optkey == "-c":
            config_fpath = optvalue
        else:
            print "Unknown option", optkey
            usage(argv)
    if not config_fpath:
        usage(argv)
    
    ctx = {}
    ctx["rt"] = {}
    ctx["rt"]["mode"] = Invoker.GLOBAL
    ctx["rt"]["clusterid"] = ""
    ctx["rt"]["hostid"] = ""
    ctx["rt"]["has_readline"] = False
    ctx["lock"] = None

    feature_test(ctx["rt"])
    if ctx["rt"]["has_readline"]:
        ctx["lock"] = threading.Lock()

    ctx["logger"] = Log(sys.stdout)
    ctx["config"] = Configure(config_fpath)
    ctx["reactor"] = Reactor(ctx)
    
    ctx["sshagents"] = {}
    for hostid in ctx["config"]["Hosts"].keys():
        ctx["sshagents"][hostid] = SSHAgent(hostid, ctx)
    
    ctx["invoker"] = Invoker(ctx)
    ctx["kbagent"] = KBAgent(ctx)

    if ctx["rt"]["has_readline"]:
        ctx["kbagent"].start()
    else:
        ctx["kbagent"].open()
        ctx["invoker"].prompt()

    ctx["reactor"].run()

if __name__ == "__main__":
    main(sys.argv)
